import { getWxConfig } from "@/service/api/sp-common/config";
import { router } from "@/router";
import Vue from "vue";
import { appGetStorage, appSetStorage } from "@/utils/storage";
import {
  Pub_User_App_Config_Cache,
  Pub_User_App_Tabbar_Cache,
  Pub_User_ThemeColor_Cache,
} from "@/const/application/base";
import { themeColor } from "@/const/theme/color";
let reLoadConfigNum = 0;
const state = {
  themeColor: appGetStorage(Pub_User_ThemeColor_Cache) || themeColor.primary, //主题色
  appConfig: appGetStorage(Pub_User_App_Config_Cache) || {}, //整个配置
  active: null, //tabbar激活状态
  tabBarList: appGetStorage(Pub_User_App_Tabbar_Cache) || [], //tabbar列表
  innitStartPage: false, //启动页是否展现过的状态
};
const mutations = {
  SET_THEME_COLOR: (state, val) => {
    state.themeColor = val;
  },
  SET_APP_CONFIG: (state, val) => {
    state.appConfig = val;
  },
  SET_ACTIVE: (state, val) => {
    state.active = val;
  },
  SET_TABBAR_LIST: (state, val) => {
    state.tabBarList = val;
  },
  SET_START_PAGE_INNIT: (state) => {
    state.innitStartPage = true;
  },
};
const actions = {
  async getUserWxConfig({ commit, state, dispatch }) {
    const res = await getWxConfig().catch((err) => {
      // console.log("报错了", err);
      reLoadConfigNum += 1;
      if (reLoadConfigNum <= 5) {
        dispatch("getUserWxConfig");
      }
    });
    if (res) {
      const { tabBarList, color } = res;
      if (router.enterPath) {
        const index = tabBarList.findIndex((v) =>
          v.openPath.includes(router.enterPath)
        );
        if (index > -1 && index !== 0) {
          uni.reLaunch({
            url: tabBarList[index].openPath,
          });
          commit("SET_ACTIVE", tabBarList[index].id);
        }
      } else if (!state.active) {
        uni.reLaunch({
          url: tabBarList[0].openPath,
        });
        commit("SET_ACTIVE", tabBarList[0].id);
      }
      console.log("应用配置", res);
      commit("SET_TABBAR_LIST", tabBarList);
      appSetStorage(Pub_User_App_Tabbar_Cache, tabBarList);
      Vue.prototype.$theme.themeColor.primary = color; //低代码主题色设置
      appSetStorage(Pub_User_ThemeColor_Cache, color);
      commit("SET_THEME_COLOR", color);
      appSetStorage(Pub_User_App_Config_Cache, res);
      commit("SET_APP_CONFIG", res);
    }
  },
  switchTab({ commit, state }, data) {
    commit("SET_ACTIVE", state.tabBarList[data].id);
    uni.reLaunch({
      url: state.tabBarList[data].openPath,
    });
  },
  setStartPageInnit({ commit, state }) {
    commit("SET_START_PAGE_INNIT");
  },
};

const getters = {
  activeIndex(state) {
    return state.list.findIndex((item) => item.id === state.active);
  },
};

export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations,
};
